package com.ruoyi.kindergarten.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import javax.xml.bind.DatatypeConverter;

import javax.annotation.Resource;

@Service
public class MqttCommandService {
    @Resource(name = "mqttPublishChannel")
    private MessageChannel mqttPublishChannel;

    @Value("${mqtt.pub-topic}")
    private String pubTopic;

    public boolean sendHexCommand(String HexCommand) {
        try{
            byte[] bytes = DatatypeConverter.parseHexBinary(HexCommand);
            boolean mqttTopic = mqttPublishChannel.send(
                    MessageBuilder.withPayload(bytes)
                            .setHeader("mqtt_topic", pubTopic)
                            .build()
            );
            if(mqttTopic){
                System.out.println("指令发送成功：16进制=" + HexCommand + "，字节=" + bytesToHex(bytes));
            }else {
                System.out.println("指令发送失败：通道未接收消息（可能MQTT未连接）");
            }
            return mqttTopic;

        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return false;
    }
    private byte[] hexStringToBytes(String hexString) {
        // 去除字符串中的空格（防前端传参时误加）
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        // 每2个字符对应1个字节
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    // --------------------------
    // 工具方法：字节数组转16进制字符串（用于日志打印）
    // --------------------------
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

}
